package com.example.sample_for_work;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

public class ViewPagerItemView extends FrameLayout {
	
	private ImageView albumImg;
	private TextView albumText;
	
	private Bitmap bitmap;
	private JSONObject jsonobj;
	
	public ViewPagerItemView(Context context){
		super(context);
		setupView();
	}
	
	public ViewPagerItemView(Context context,AttributeSet attrs){
		super(context, attrs);
		setupView();
	}
	
	private void setupView(){
		LayoutInflater inflater = LayoutInflater.from(getContext());  
        View view = inflater.inflate(R.layout.viewitem, null);  
          
        albumImg = (ImageView)view.findViewById(R.id.album_imgview);  
        albumText = (TextView)view.findViewById(R.id.album_name);   
        addView(view);
	}
	
	public void setData(JSONObject obj){
		this.jsonobj = obj;
		File root = new File(Environment.getExternalStorageDirectory()+"");
		try{
			int resId = obj.getInt("resid");
			String name = obj.getString("name");
//			albumImg.setImageResource(resId);
			bitmap = BitmapFactory.decodeFile(root+"/"+name);
			albumImg.setImageBitmap(bitmap);
			albumText.setText(name);
		} catch (JSONException e){
			e.printStackTrace();
		}
	}
	
	public void recycle(){
		albumImg.setImageBitmap(null);
		if((this.bitmap == null) || (this.bitmap.isRecycled()))
			return;
		this.bitmap.recycle();
		this.bitmap = null;
	}
	
	public void reload(){
		File root = new File(Environment.getExternalStorageDirectory()+"");
		try{
			int resId = jsonobj.getInt("resid");
			String name = jsonobj.getString("name");
			bitmap = BitmapFactory.decodeFile(root+"/"+name);
			albumImg.setImageBitmap(bitmap);
//			albumImg.setImageResource(resId);
		}catch(JSONException e){
			e.printStackTrace();
		}
	}
	
}